//
//  WYPersonMessageController.m
//  Boss
//
//  Created by admin on 2018/7/3.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYPersonMessageController.h"
#import "WYPersonMessageCell.h"
#import "WYPersonMessageHeaderCell.h"
#import "WYEditMessageController.h"
#import "WYDataPicker.h"
#import "CZHAddressPickerView.h"
#import "WYUserMessage.h"
#import "WYUploadModel.h"
#import "WYVIPController.h"
#import "CJNewVipController.h"
#import "UIImage+WYSaveImage.h"
@interface WYPersonMessageController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)  WYDataPicker *datePicker;

@property (nonatomic, copy) NSString *province;

@property (nonatomic, copy) NSString *city;

@property (nonatomic, copy) NSString *area;

@property (nonatomic,strong)NSArray *nameArray;

@property (nonatomic,strong)WYUserMessage *userMessage;

@property (nonatomic,strong)NSString *pathString;

@property (nonatomic,strong)WYUploadModel *model;

@end

@implementation WYPersonMessageController
-(NSArray *)nameArray
{
    if (!_nameArray) {
//        _nameArray = @[@[@"头像",@"昵称",@"性别",@"年龄",@"常驻城市",@"绑定手机号",@"BOSS VIP"],@[@"职位",@"邮箱",@"公司网址",@"公司地址"]];
        _nameArray = @[@[@"头像",@"昵称",@"性别",@"年龄",@"常驻城市",@"绑定手机号",@"BOSS VIP"]];
    }
    return _nameArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    if (@available(iOS 11, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
        
    }
    //[self loadData];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadData];
}

-(void)loadData
{
    WEAKSELF
    [WYHttpServer getUserMessageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
      
        if (success) {
            weakSelf.userMessage = [WYUserMessage getUserMessageFromJson:response[@"result"]];
            [weakSelf.tableView reloadData];
        }
        
    }];
}

-(void)setupUI
{
    self.navigationItem.title = @"个人资料";
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYPersonMessageHeaderCell" bundle:nil] forCellReuseIdentifier:@"WYPersonMessageHeaderCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYPersonMessageCell" bundle:nil] forCellReuseIdentifier:@"WYPersonMessageCell"];
    self.tableView.tableFooterView = [[UIView alloc]init];
    WEAKSELF
    WYDataPicker *datePicker = [[WYDataPicker alloc]initWithFrame:CGRectMake(0, kScreenHeight-214, kScreenWidth, 214)];
    datePicker.complete = ^(NSString *date) {
//        weakSelf.ageLabel.text =[NSString stringWithFormat:@"%.0f",[weakSelf calculateAge:date]];
//        weakSelf.date = date;
        [weakSelf editAgeWithdate:date];
    };
    [self.view addSubview:datePicker];
    datePicker.hidden = YES;
    self.datePicker = datePicker;
    [self.datePicker setType:@"11"];
    self.tableView.backgroundColor = [UIColor hexStringToColor:@"#f7f7f7" alpha:1.0];
    
    
}
-(void)editAgeWithdate:(NSString *)date
{
    
    WEAKSELF
    [WYHttpServer editUserMessageWithHeadImgUrl:nil WithUserName:nil WithSex:nil WithBirthday:date WithProvince:nil WithCity:nil WithPrefecture:nil SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf loadData];
        }
        
        
    }];
    
    
}
- (double )calculateAge:(NSString *)str {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";
    NSDate *birthDay = [dateFormatter dateFromString:str];
    //获取时间戳，时间戳是负数
    NSTimeInterval time = [birthDay timeIntervalSinceNow];
    double year = floor(ABS(time)/(3600.0 * 24 * 365)); //3600秒 * 24小时*365天
    return year;
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.nameArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.nameArray[section] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *name = self.nameArray[indexPath.section][indexPath.row];
    
    
    if (indexPath.row==0&&indexPath.section==0) {
        WYPersonMessageHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYPersonMessageHeaderCell" forIndexPath:indexPath];
        if (!cell) {
            cell =[[NSBundle mainBundle]loadNibNamed:@"WYPersonMessageHeaderCell" owner:nil options:nil].firstObject;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.nameLabel.text = name;
        if (self.userMessage.url.length) {
            [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:self.userMessage.url] placeholderImage:[UIImage imageNamed:@"logo_place"]];
        }
        
        
        return cell;
    }
    WYPersonMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYPersonMessageCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"WYPersonMessageCell" owner:nil options:nil].firstObject;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.nameLabel.text = name;
    
    if (indexPath.section==0) {
        if (indexPath.row==5) {
            cell.rightImageView.hidden=YES;
            cell.rightJ.constant=0;
            cell.rightImageView.width=0;
            if (self.userMessage.phone.length) {
                cell.rightNameLabel.text = [self numberSuitScanf:self.userMessage.phone];
            }
            
        }
        if (indexPath.row==1) {
            if(self.userMessage.userName.length){
                cell.rightNameLabel.text = self.userMessage.userName;
            }else{
                cell.rightNameLabel.text = @"未设置";
            }
        }
        if (indexPath.row==2) {
            if(self.userMessage.sex.length){
                if (self.userMessage.sex.integerValue) {
                    cell.rightNameLabel.text = @"帅哥";
                }else{
                    cell.rightNameLabel.text = @"美女";
                }
            }else{
                cell.rightNameLabel.text = @"未设置";
            }
        }
        
        if (indexPath.row==3) {
            if(self.userMessage.birthday.length){
                cell.rightNameLabel.text =[NSString stringWithFormat:@"%.0f",[self calculateAge:self.userMessage.birthday]];
            }else{
                cell.rightNameLabel.text = @"未设置";
            }
        }
        if (indexPath.row==4) {
            if(self.userMessage.city.length){
                if ([self.userMessage.province isEqualToString:self.userMessage.city]) {
                    cell.rightNameLabel.text = self.userMessage.city;
                }else{
                    cell.rightNameLabel.text =[NSString stringWithFormat:@"%@ %@",self.userMessage.province,self.userMessage.city];
                }
                
                
            }else{
                cell.rightNameLabel.text = @"未设置";
            }
            
        }
    }
    
   
    cell.rightNameLabel.textColor = [UIColor hexStringToColor:@"#333333" alpha:1.0];
    cell.rightNameLabel.font = [UIFont systemFontOfSize:16];
    cell.nameLabel.textColor = [UIColor hexStringToColor:@"#222222" alpha:1.0];
    cell.nameLabel.font = [UIFont systemFontOfSize:16];
    
    
    return cell;
    
    
    
    
}

-  (NSString *)numberSuitScanf:(NSString*)number{
    
    NSMutableString *phoneStr = [NSMutableString stringWithString:number];
    
    NSString *regex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    // 判断当前字符串是否为手机号
    BOOL isMatch = [pred evaluateWithObject:phoneStr];
    if (isMatch) {
        [phoneStr replaceCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    
    return [NSString stringWithString:phoneStr];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor hexStringToColor:@"#f7f7f7" alpha:1.0];
    
    UILabel *label = [[UILabel alloc]init];
    [view addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.centerY.mas_equalTo(view);
    }];
    label.font = [UIFont systemFontOfSize:16];
    label.textColor = [UIColor hexStringToColor:@"#222222" alpha:1.0];
    if (section==0) {
        label.text =  @"个人资料";
    }else{
        label.text =  @"名片信息";
    }
    
    
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 80-16;
    }
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WEAKSELF
    self.datePicker.hidden = YES;
    
    if (indexPath.section==0) {
        if (indexPath.row==1) {
            WYEditMessageController *evc= [[WYEditMessageController alloc]init];
            evc.navTitle = @"修改昵称";
            evc.tag = 3;
            evc.textFieldText = self.userMessage.userName;
            evc.placeHoder = @"请输入您的昵称";
            [self.navigationController pushViewController:evc animated:YES];
        }
        if (indexPath.row==2) {
            WYPersonMessageCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"帅哥" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf eidtSexWithSex:@"1"];
            }];
            
            UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"美女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf eidtSexWithSex:@"0"];
            }];
            
            [alertController addAction:action1];
            [alertController addAction:action2];
            [alertController addAction:action3];
            if (IS_IPAD) {
                UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController];
                popPresenter.sourceView = cell;
                popPresenter.sourceRect = cell.bounds;
                [self presentViewController:alertController animated:YES completion:nil];
                
            }else{
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        
        if (indexPath.row==3) {
            self.datePicker.hidden = NO;
        }
        if (indexPath.row==4) {
            WEAKSELF
            [CZHAddressPickerView areaPickerViewWithProvince:self.province city:self.city area:self.area areaBlock:^(NSString *province, NSString *city, NSString *area) {
                // CZHStrongS elf(self);
                weakSelf.province = province;
                weakSelf.city = city;
                weakSelf.area = area;
                [weakSelf editCity];
            }];
        }
        if (indexPath.row==0) {
            WYPersonMessageHeaderCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self; //设置代理
            imagePickerController.allowsEditing = YES;
            
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
            }];
            
            
            UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [weakSelf presentViewController:imagePickerController animated:YES completion:nil];
            }];
            [alertController addAction:action1];
            [alertController addAction:action2];
            [alertController addAction:action3];
            if (IS_IPAD) {
                UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController];
                popPresenter.sourceView = cell;
                popPresenter.sourceRect = cell.bounds;
                [self presentViewController:alertController animated:YES completion:nil];
                
            }else{
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        
        if (indexPath.row==6) {
            CJNewVipController *vpc = [[CJNewVipController alloc]init];
            [self.navigationController pushViewController:vpc animated:YES];
        }
    }
    
    
   
    
    
    
    
    
}
-(void)editCity
{
    WEAKSELF
    [WYHttpServer editUserMessageWithHeadImgUrl:nil WithUserName:nil WithSex:nil WithBirthday:nil WithProvince:self.province WithCity:self.city WithPrefecture:self.area SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf loadData];
        }
        
        
    }];
}


-(void)eidtSexWithSex:(NSString *)sex
{
    WEAKSELF
    [WYHttpServer editUserMessageWithHeadImgUrl:nil WithUserName:nil WithSex:sex WithBirthday:nil WithProvince:nil WithCity:nil WithPrefecture:nil SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf loadData];
        }
        
        
    }];
    
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //[self showLoading:@""];
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString *path = [photo QCloudTempFilePathWithExtension:@"PNG"];
    self.pathString = path;
    [UIImagePNGRepresentation(photo) writeToFile:path atomically:YES];
    WEAKSELF
    [WYHttpServer uploadImageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        WYUploadModel *model = [WYUploadModel getupLoadModelFromJson:response[@"result"]];
        [weakSelf upLoadWithPath:model.uploadUrl];
        weakSelf.model = model;
        
        
    }];
}
-(void)upLoadWithPath:(NSString *)path
{
    WEAKSELF
    [WYHttpServer PUTWithURLStr:path filePath:self.pathString SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf editHeaderImageview];
        }else{
            
        }
        
    }];
}

-(void)editHeaderImageview
{
    NSString *str = [NSString stringWithFormat:@"%@!default",self.model.visitUrl];
    NSLog(@"%@",str);
    
    WEAKSELF
    [WYHttpServer editUserMessageWithHeadImgUrl:[NSString stringWithFormat:@"%@!default",self.model.visitUrl] WithUserName:nil WithSex:nil WithBirthday:nil WithProvince:nil WithCity:nil WithPrefecture:nil SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf loadData];
        }
        
        
        
    }];
    
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (@available(iOS 11, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    }
}


- (UITableView *)tableView
{
    if (_tableView == nil) {
        CGRect frame = CGRectMake(0, self.navHeight, kScreenWidth, kScreenHeight-self.navHeight);
        _tableView = [[UITableView alloc] initWithFrame:frame
                                                  style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    }
    return _tableView;
}



@end
